using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.Query;

namespace NBusiness.MySql.Query
{
    public class MySqlTable : ITable
    {
        #region Member fields and properties
        private string _name;
        private string _alias; 
        #endregion

        #region Constructors
        public MySqlTable() { }
        public MySqlTable(string name)
            : this(name, null)
        { }
        public MySqlTable(string name, string alias)
        {
            _name = name;
            _alias = alias;
        }
        #endregion

        #region ITable Members

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Alias
        {
            get { return _alias; }
            set { _alias = value; }
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("`" + _name + "`");
            if (_alias != null)
                builder.Append(" AS `" + _alias + "`");

            return builder.ToString();
        }

        #endregion

        #region Operator overloads
        public static MySqlSelect operator &(MySqlTable table, MySqlBoolean e)
        {
            return new MySqlSelect(e, table);
        } 
        #endregion

        #region Helpers
        public IQuery Where(IExpression expression)
        {
            IQuery select = new MySqlSelect();
            select = select.From(this);
            select.Where(expression);
            return select;
        }

        public IQuery OrderBy(IOrder orderBy)
        {
            return new MySqlSelect(this).OrderBy(orderBy);
        }
        public IQuery OrderBy(SortOrder order, params IColumn[] columns)
        {
            return new MySqlSelect(this).OrderBy(order, columns);
        }

        public IQuery GroupBy(params IColumn[] groupBy)
        {
            return new MySqlSelect(this).GroupBy(groupBy);
        }
        public IQuery Select(params ISelectable[] selectable)
        {
            return new MySqlSelect(this).Select(selectable);
        }

        public IJoin InnerJoin(IExpression on)
        {
            return new MySqlInnerJoin(this, on);
        }

        public IQuery JoinWith(params IJoin[] joins)
        {
            List<ISource> sources = new List<ISource>(joins);
            sources.Insert(0, this);
            return new MySqlSelect(null, sources.ToArray());           
        }
        #endregion
    }
}
